package com.app.shop.demo.activitys;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.app.shop.demo.R;
import com.app.shop.demo.beans.User;
import com.app.shop.mylibrary.base.BaseActivity;
import com.app.shop.mylibrary.beans.EventMessage;
import com.app.shop.mylibrary.utils.SharedPreferencesUtil;
import com.app.shop.mylibrary.utils.StringUtil;
import com.app.shop.mylibrary.utils.ToastUtil;

import org.litepal.crud.DataSupport;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

public class  LoginActivity  extends BaseActivity {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.inputMobile)
    EditText inputMobile;
    @BindView(R.id.inputpwd)
    EditText inputpwd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);

        tvTitle.setText("登录");
    }

    @OnClick({R.id.imgv_return, R.id.toLogin, R.id.tv_register})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.imgv_return:

                onBackPressed();
                break;

            case R.id.toLogin:

                if (StringUtil.isEmpty(inputMobile.getText().toString())) {
                    ToastUtil.showToast(this, "请输入手机号");
                    return;
                }

                if (StringUtil.isEmpty(inputpwd.getText().toString())) {
                    ToastUtil.showToast(this, "请输入密码");
                    return;
                }


                if (isOk(inputMobile.getText().toString(), inputpwd.getText().toString())) { //密码正确
                    User user = new User();
                    user.setMobile(inputMobile.getText().toString());
                    user.setUser_name(inputMobile.getText().toString());
                    SharedPreferencesUtil.saveDataBean(this, user, "user");
                    EventBus.getDefault().post(new EventMessage(EventMessage.LOGIN));
                    finish();
                    finish();
                } else {
                    ToastUtil.showToast(this, "密码不匹配");
                }





                break;

            case R.id.tv_register:
                showActivity(LoginActivity.this, RegisterActivity.class);

                break;
        }
    }

    public static boolean isOk(String name, String pwd) {
        List<User> list = DataSupport.findAll(User.class);
        String password = "";
        for (int i = 0; i < list.size(); i++) {
            User ss = list.get(i);
            if (ss.getMobile().equals(name) && ss.getPassword().equals(pwd)) {
                return true;
            }
        }
        return false;
    }

}
